#pragma once
#include <iostream>
#include <string.h>
#include <pthread.h>

namespace ThreadMoudle
{
    typedef void (*func_t)(const std::string &name);
    class Thread
    {
    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func;

    public:
        void Excute() // 打印线程开始运行的消息
        {
            std::cout << "is running"<<std::endl;
            _isrunning=true;    //表示线程正在运行
            _func(_name);       //传入线程名称，调用回调函数
            _isrunning=false;   //线程结束

        }

    public:
        Thread(const std::string &name, func_t func) : _name(name), _func(func)
        {
            std::cout << "create" << name << "done" << std::endl;
        }
        static void *ThreadRoutine(void *args)
        {
            Thread *self=static_cast<Thread*>(args);
            self->Excute();
            return nullptr;
        }
        bool start()
        {
            int n=::pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n!=0)
            {
                return false;
            }
            return true;
        }
        std::string status()
        {
            if(_isrunning) return "isrunning";
            else return "sleep";
        }
        void stop()
        {
            if(_isrunning)
            {
                ::pthread_cancel(_tid); //如果线程正在进行，使用pthread_cancel方法停止线程
                _isrunning=false;
                std::cout << _name << " Stop" << std::endl;
            }
        }
        void join()
        {
            ::pthread_join(_tid,nullptr);//用于等待指定的线程终止，并获取该线程的返回值。
            std::cout << _name << " joined" <<std::endl;
        }
        std::string Name()
        {
            return _name;
        }
        ~Thread()
        {
        }
    };

}